import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Button, Input, message, Modal, Spin } from 'antd';
import { defaultProps } from '../../../schema';
import EditTable from '../EditTable';
import SelectListPc from '../SelectListPc';
import { PlusOutlined } from '@ant-design/icons';
import {
  getStaticGroupList,
  saveStaticGroupList,
  editStaticGroupList,
  delStaticGroupList,
  getStaticDataList,
  saveStaticDataList,
} from '../../services';
import { useForm } from '@formily/react';
import './index.less';
import { TextWidget, getMessage } from '@inbiz/react';

type IProps = {
  emit?: (type: any, ...arg: any) => void;
  onChange?: Function;
  value?: object;
} & typeof defaultProps;

const SettingView = (props: IProps) => {
  // Modal的显示控制状态
  const [isModalVisible, $isModalVisible] = useState(false);

  // 数据组
  const [groupList, $groupList] = useState([]);

  // 字典数据
  const [dataList, $dataList] = useState([]);

  // 显示添加Input
  const [showAdd, $showAdd] = useState(false);

  // 当前选中的组id
  const [active, $active] = useState<any>(null);

  // 组列表加载状态
  const [groupLoading, $groupLoading] = useState(false);

  // 表格加载状态
  const [tableLoading, $tableLoading] = useState(false);

  // 确定提交按钮状态
  const [confirmLoading, $confirmLoading] = useState(false);

  // appId
  const [appId, $appId] = useState(null);

  // 可编辑表格组件Dom
  const tableRef = useRef<any>();

  // 添加组Input的Dom节点
  const inputRef = useRef<any>();

  let info: any = useForm();

  useEffect(() => {
    let appId = info.appInfo.appId;
    $appId(appId);
  }, []);

  useEffect(() => {
    if (isModalVisible) {
      getGroupList();
    }
  }, [isModalVisible]);

  useEffect(() => {
    if (active) {
      getDataList(active);
    } else {
      $dataList([]);
    }
  }, [active]);

  // 显示增加组inpit框后自动获取焦点
  useEffect(() => {
    showAdd && inputRef.current.focus();
  }, [showAdd]);

  // 获取字典分组列表
  const getGroupList = useCallback(() => {
    $groupLoading(true);
    getStaticGroupList(appId || '')
      .then((res) => {
        $groupLoading(false);
        $groupList(res);
      })
      .catch(() => {
        $groupLoading(false);
        $active(null);
        $dataList([]);
        message.error(getMessage('EformStaticList.tips.failedToGetList'));
      });
  }, [appId]);

  // 添加组（保存已输入的组）
  const addIptChange = useCallback(
    (e) => {
      if (!e.target.value.trim()) {
        $showAdd(false);
        return;
      }
      if (groupList.some((item: any) => item.Name === e.target.value.trim())) {
        $showAdd(false);
        message.error(getMessage('EformStaticList.tips.theNameAlreadyExists'));
        return;
      }
      $groupLoading(true);
      saveStaticGroupList({ appId: appId || '', name: e.target.value })
        .then((res) => {
          getGroupList();
          $showAdd(false);
          message.success(getMessage('EformStaticList.tips.groupSavedSuccessfully'));
        })
        .catch(() => {
          message.error(getMessage('EformStaticList.tips.failedToSaveTheGroup'));
          $showAdd(false);
          $groupLoading(false);
        });
    },
    [groupList, appId],
  );

  // 删除组
  const delGroup = useCallback(
    (key: string) => {
      $groupLoading(true);
      const arr = groupList.filter((item: any) => item.Key !== key);
      delStaticGroupList({
        appId: appId || '',
        key: key,
      })
        .then(() => {
          $groupList(arr);
          $active(null);
          $groupLoading(false);
          message.success(getMessage('EformStaticList.tips.groupDeletedSuccessfully'));
        })
        .catch(() => {
          $groupLoading(false);
          message.error(getMessage('EformStaticList.tips.failedToDeleteGroup'));
        });
    },
    [groupList, appId],
  );

  // 修改组
  const editGroup = useCallback(
    (key: string, name: string) => {
      if (!name || name.trim() === '') {
        message.error(getMessage('EformStaticList.tips.nameCannotBeEmpty'));
        return;
      }
      const filter: any[] = groupList.filter((item: any) => item.Name === name);
      if (filter.length) {
        if (filter[0].Key !== key) {
          message.error(getMessage('EformStaticList.tips.theNameAlreadyExists'));
        }
        return;
      }
      $groupLoading(true);
      editStaticGroupList({
        appId: appId || '',
        key: key,
        name: name,
      })
        .then(() => {
          getGroupList();
          message.success(getMessage('EformStaticList.tips.groupSavedSuccessfully'));
        })
        .catch(() => {
          $groupLoading(false);
          message.error(getMessage('EformStaticList.tips.failedToSaveTheGroup'));
        });
    },
    [groupList, appId],
  );

  // 获取分组下字典列表
  const getDataList = useCallback(
    (groupKey: string) => {
      $tableLoading(true);
      getStaticDataList({
        appId: appId || '',
        groupKey: groupKey,
      })
        .then((res) => {
          $tableLoading(false);
          $dataList(res);
        })
        .catch(() => {
          $tableLoading(false);
          message.error(getMessage('EformStaticList.tips.failedToGetDictionary'));
        });
    },
    [appId],
  );

  // 保存分组下字典
  const dataListSave = useCallback(
    (list: any[]) => {
      $tableLoading(true);
      saveStaticDataList({
        appId: appId || '',
        groupKey: active,
        items: list,
      })
        .then(() => {
          $tableLoading(false);
          message.success(getMessage('EformStaticList.tips.savedSuccessfully'));
        })
        .catch(() => {
          $tableLoading(false);
          message.error(getMessage('EformStaticList.tips.saveFailed'));
        });
    },
    [appId, active],
  );

  // 显示配置数据源Modal
  const showModal = () => {
    $isModalVisible(true);
  };

  // 选中组数据后关闭Modal框
  const handleOk = useCallback(async () => {
    let data = await tableRef.current.submit();
    if (Array.isArray(data)) {
      $confirmLoading(true);
      let arr = data.map((item, idx) => ({
        columnSort: idx,
        value: item.Value,
        text: item.Text,
      }));
      saveStaticDataList({
        appId: appId || '',
        groupKey: active,
        items: arr,
      })
        .then(() => {
          $isModalVisible(false);
          props.onChange && props.onChange(active);
          $confirmLoading(false);
        })
        .catch(() => {
          $confirmLoading(false);
        });
    }
  }, [appId, active]);

  // 不保存关闭Modal框（取消）
  const handleCancel = () => {
    $isModalVisible(false);
  };

  // 显示增加组input框
  const addGroup = () => {
    $showAdd(true);
  };

  return (
    <div className="setting-nav">
      <Button type="primary" onClick={showModal}>
        <TextWidget>EformStaticList.configure</TextWidget>
      </Button>
      <Modal
        title={getMessage('EformStaticList.tips.configureDataDictionary')}
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
        okText={getMessage('EformStaticList.confirm')}
        cancelText={getMessage('EformStaticList.cancel')}
        destroyOnClose={true}
        width={740}
        getContainer={false}
        confirmLoading={confirmLoading}
        isMove
      >
        <div className="eform-static-list">
          <div className="left-content">
            <Spin spinning={groupLoading}>
              <div className="top-nav">
                <span>
                  <TextWidget>EformStaticList.DirectoryList</TextWidget>
                </span>
                <PlusOutlined onClick={addGroup} />
              </div>
              <div className="list-nav">
                <SelectListPc
                  dataSource={groupList}
                  onSelect={(groupId: string | number) => {
                    $active(groupId);
                  }}
                  active={active || null}
                  del={(groupId: string) => {
                    delGroup(groupId);
                  }}
                  edit={(groupId: string, name: string) => {
                    editGroup(groupId, name);
                  }}
                />
                {showAdd ? (
                  <Input ref={inputRef} onBlur={addIptChange} onPressEnter={addIptChange} />
                ) : null}
              </div>
            </Spin>
          </div>
          <div className="right-content">
            <Spin spinning={tableLoading}>
              {/* <EditTable gRef={tableRef} data={toJS(props.value)} groupId={active} /> */}
              <EditTable gRef={tableRef} data={dataList} groupId={active} save={dataListSave} />
            </Spin>
          </div>
        </div>
      </Modal>
    </div>
  );
};

export default SettingView;
